/**
 * [default 跨页面通信hook]
 *
 */
export default function (name: string) {
	const broadcast = new BroadcastChannel(name)
	let removeBroadcast: Function

	function broadcastEmit(data?: any) {
		broadcast.postMessage(data || null)
	}

	function broadcastListen(fn: Function) {
		const handler = e => fn && fn(e.data)
		broadcast.addEventListener('message', handler)
		removeBroadcast = () => broadcast.removeEventListener('message', handler)
		return removeBroadcast
	}

	onUnmounted(() => removeBroadcast && removeBroadcast())
	onDeactivated(() => removeBroadcast && removeBroadcast())

	return { broadcastEmit, broadcastListen }
}
